package so.shanku.essential.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentTransaction;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.download.DownLoadQueue;
import net.tsz.afinal.download.DownloadService;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import net.tsz.afinal.sdcard.SdcardHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.fragment.*;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.view.WihteRoundCornersDialog;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Jaelyn on 2015/8/17 0017.
 */
public class MainActivity extends BaseActivity implements ServiceConnection {
    private int currentSelectItem = -1;
    //底部导航栏
    @ViewInject(id = R.id.tab_bottom_layout)
    private RadioGroup tab_bottom_layout;

    /**
     * 选项卡展示页
     */
    @ViewInject(id = R.id.fragment_layout)
    private LinearLayout fragment_layout;

    /**
     * 保存点击过得fragment
     */
    private HashMap<Integer, BaseFragment> fragments = new HashMap();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        tab_bottom_layout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                setSelectItem(checkedId);
            }
        });
        setSelectItem(0);
        //upversion();
    }

    /**
     * 检测版本
     */
    private void upversion() {
        if (!SdcardHelper.ExistSDCard()) {
            toast.showToast(R.string.nosdcard);
        } else {
            Intent e = new Intent(this, DownloadService.class);
            this.startService(e);
            this.bindService(e, this, BIND_AUTO_CREATE);

            GetDataQueue queue = new GetDataQueue();
            queue.setActionName(GetDataConfing.Action_selectAppVersionInfo);
            queue.setParams(new HashMap<String, String>());
            queue.setCallBack(callBack);
            queue.setWhat(GetDataConfing.What_selectAppVersionInfo);
            getDataUtil.getData(queue);
        }

    }

    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetDataQueue entity) {
            loadingToast.dismiss();
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_selectAppVersionInfo) {

                        List<JsonMap<String, Object>> infoData = JsonParseHelper
                                .getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        if (infoData.size() == 0) {
                            toast.showToast(R.string.app_version_newest);
                        } else {
                            JsonMap<String, Object> info = infoData.get(0);
                            if (info.getStringNoNull("VersionNo").equals(myApplication.getVersionName())
                                    || "".equals(info.getStringNoNull("VersionNo"))
                                    || "".equals(info.getStringNoNull("VersionPath"))) {
                                toast.showToast(R.string.app_version_newest);
                            } else {
                                showNewVersion(info);
                            }
                        }
                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);
            }

        }

    };
    /**
     * 提示用户有新版本
     */
    String apkDownLoadPath;

    private void showNewVersion(JsonMap<String, Object> info) {
        apkDownLoadPath = info.getStringNoNull("VersionPath");
        builder = new WihteRoundCornersDialog(mContext,
                R.style.ExitDialogStyle, 2, callBackdialog1);
        builder.setTitletext(R.string.app_version_select);
        builder.setMessagetext(info.getStringNoNull("Description"));
        builder.setButtonText(R.string.app_version_iknow, R.string.app_version_update);
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog1 = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:

                    break;
                case 2:
                    String appName = getString(R.string.app_name);
                    startDownload(apkDownLoadPath, appName + ".apk", appName, 1);

                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };


    private DownloadService.DownloadServiceBinder binder;

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        this.binder = (DownloadService.DownloadServiceBinder) service;
//        if(!this.isToStop) {
//            this.queue = this.binder.getService().addQueue(this.queue);
//        }
    }

    private DownLoadQueue queue;

    private void startDownload(String url, String fileName, String title, int id) {
        this.queue = new DownLoadQueue();
        this.queue.setId(id);
        this.queue.setIconResId(R.drawable.app_icon);
        this.queue.setCancel(false);
        this.queue.setDownLoadedPath(Constant.productPath + fileName);
        this.queue.setDownLoadUrl(url);
        this.queue.setName(title);
        this.queue.setOpenFileType("application/vnd.android.package-archive");
        this.queue.setDownLoadedAutoOpenFile(true, "application/vnd.android.package-archive");//自动打开app

        binder.getService().addQueue(this.queue);

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    @Override
    protected void onDestroy() {
//        unbindService(this);
        super.onDestroy();
    }

    //设置选中项和展示
    public void setSelectItem(int checkedId) {
        int selectItem = 0;
        if (checkedId == R.id.find_page_tv) {
            selectItem = 0;
        } else if (checkedId == R.id.shopping_page_tv) {
            selectItem = 1;
        } else if (checkedId == R.id.home_page_tv) {
            selectItem = 2;
        } else if (checkedId == R.id.community_page_tv) {
            selectItem = 3;
        } else if (checkedId == R.id.userCenter_page_tv) {
            selectItem = 4;
        }

        if (currentSelectItem != selectItem) {

            currentSelectItem = selectItem;
            switch (selectItem) {
                case 0:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        FindFragment findFragment = new FindFragment();
                        fragments.put(selectItem, findFragment);
                        replaceView(findFragment);
//                        ShopMallFragment shopMallFragment = new ShopMallFragment();
//                        fragments.put(selectItem, shopMallFragment);
//                        replaceView(shopMallFragment);
                    }
                    //replaceView(new HomePageFragment());

                    break;
                case 1:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        ShopMallFragment shopMallFragment = new ShopMallFragment();
                        fragments.put(selectItem, shopMallFragment);
                        replaceView(shopMallFragment);
//                        FindFragment findFragment = new FindFragment();
//                        fragments.put(selectItem, findFragment);
//                        replaceView(findFragment);
                    }
                    break;
                case 2:
                	Intent intent = new Intent(mContext, PublishedActivity.class);
                	startActivity(intent);
//                	finish();
//                    if (fragments.get(selectItem) != null) {
//                        replaceView(fragments.get(selectItem));
//                    } else {
//                        ShoppingMallFragment shoppingMallFragment = new ShoppingMallFragment();
//                        fragments.put(selectItem, shoppingMallFragment);
//                        replaceView(shoppingMallFragment);
//                    }
                    break;
                case 3:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        CommunityFragment shoppingBrandFragment = new CommunityFragment();
                        fragments.put(selectItem, shoppingBrandFragment);
                        replaceView(shoppingBrandFragment);
                    }
                    break;
                case 4:
                    if (fragments.get(selectItem) != null) {
                        replaceView(fragments.get(selectItem));
                    } else {
                        UserCenterFragment userCenterFragment = new UserCenterFragment();
                        fragments.put(selectItem, userCenterFragment);
                        replaceView(userCenterFragment);
                    }
                    break;
                default:
                    break;
            }

        }
    }


    private BaseFragment currentFragment;

    private void replaceView(BaseFragment fragment) {
        if (currentFragment != fragment) {
            FragmentTransaction transaction = this.getSupportFragmentManager()
                    .beginTransaction();
//			FragmentTransaction transaction = mFragmentMan.beginTransaction().setCustomAnimations(
//					android.R.anim.fade_in, R.anim.slide_out);
            if (currentFragment != null) {
                if (!fragment.isAdded()) {    // 先判断是否被add过
                    transaction.hide(currentFragment).add(R.id.fragment_layout, fragment).commit(); // 隐藏当前的fragment，add下一个到Activity中
                } else {
                    transaction.hide(currentFragment).show(fragment).commit(); // 隐藏当前的fragment，显示下一个
                }
            } else {
                transaction.add(R.id.fragment_layout, fragment).commit(); // add下一个到Activity中
            }
            currentFragment = fragment;
        }
    }

    @Override
    public void onBackPressed() {
        if (currentFragment.backKeyClick()) {
            super.onBackPressed();
        } else {
            showExitDialog();
        }

    }

    WihteRoundCornersDialog builder;

    private void showExitDialog() {

        builder = new WihteRoundCornersDialog(this,
                R.style.ExitDialogStyle, 2, callBackdialog);
        builder.setTitletext("温馨提示");
        builder.setMessagetext("是否确认退出？");
        builder.setButtonText("取消", "确定");
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:

                    break;
                case 2:
                    MainActivity.this.finish();
                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };

}